package deepr.filter;

import deepr.lib.FilterLib;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public abstract class DbFilterBehavior implements DbFilterActionBehavior, DbForeignFilterBehavior {

    private HashMap<Integer, HashMap<String, FilterRelay>> depthObjectFilter = new HashMap<>();

    public void resetDepthObjectFilter() {
        depthObjectFilter = new HashMap<>();
    }


    public StringBuilder getPropertyFilter(FilterParser parser, FilterRelay filterRelay) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, StringBuilder> entry : filterRelay.getPropertyFilter().entrySet()) {
            if (entry.getValue().length() > 0) {
                FilterLib.appendJoiner(sb, parser.getJoiner());
                sb.append(entry.getValue());
            }
        }
        return sb;
    }


    public void appendProperty(Integer depth, String parent, String object, String property, StringBuilder newSb, String joiner) {
        HashMap<String, FilterRelay> objMap = depthObjectFilter.getOrDefault(depth, new HashMap<>());
        FilterRelay foreign = objMap.getOrDefault(object, new FilterRelay(parent));
        foreign.appendProperty(property, newSb, joiner);
        objMap.put(object, foreign);
        depthObjectFilter.put(depth, objMap);
    }

    public void appendJsonArray(Integer depth, String parent, String object, String property, StringBuilder newSb, String joiner) {
        HashMap<String, FilterRelay> objMap = depthObjectFilter.getOrDefault(depth, new HashMap<>());
        FilterRelay foreign = objMap.getOrDefault(object, new FilterRelay(parent));
        foreign.appendJsonArray(property, newSb, joiner);
        objMap.put(object, foreign);
        depthObjectFilter.put(depth, objMap);
    }

}
